package com.webserver.controller;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;
import com.webserver.vo.Article;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

/**
 * 处理与文章相关的业务
 */
public class ArticleController {
    public static final String ARTICLE_DIR="./articles/";

    static {
        File dir=new File(ARTICLE_DIR);
        if(!dir.exists()){
            dir.mkdirs();
        }
    }

    public void writeArticle(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理发表文章....");
        String title=request.getParameter("title");
        String author=request.getParameter("author");
        String content=request.getParameter("content");

        if(title==null || author==null || content==null){
            File file=new File("./webapps/myweb/article_fail.html");
            response.setEntity(file);
            return;
        }

        try(
                FileOutputStream fos=new FileOutputStream(ARTICLE_DIR+title+".obj");
                ObjectOutputStream oos=new ObjectOutputStream(fos);
        ){
            Article article=new Article(title,author,content);
            oos.writeObject(article);
            File file=new File("./webapps/myweb/article_success.html");
            response.setEntity(file);
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("发表文章处理完毕！");
    }
}
